using B.S.Infratrctrue;
using B.S.Requst;
using MediatR;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using B.S.Domain.InvoiceManagement;

namespace B.S.Data.MES.API.Applications.B.S.KApplications.Command.InvoiceCommand
{
    /// <summary>
    /// 添加销售发票命令处理程序
    /// 处理销售发票的新增逻辑
    /// </summary>
    public class AddSalesInvoiceCommandHandler : IRequestHandler<AddSalesInvoiceCommand, APIRequst<int>>
    {
        private readonly IBaseRepository<SalesInvoice> _salesInvoiceRepository;
        private readonly IBaseRepository<SalesInvoiceDetail> _salesInvoiceDetailRepository;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="salesInvoiceRepository">销售发票仓储</param>
        /// <param name="salesInvoiceDetailRepository">销售发票明细仓储</param>
        public AddSalesInvoiceCommandHandler(IBaseRepository<SalesInvoice> salesInvoiceRepository, IBaseRepository<SalesInvoiceDetail> salesInvoiceDetailRepository)
        {
            _salesInvoiceRepository = salesInvoiceRepository;
            _salesInvoiceDetailRepository = salesInvoiceDetailRepository;
        }

        /// <summary>
        /// 处理添加销售发票的命令
        /// </summary>
        /// <param name="request">添加销售发票命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>处理结果，返回创建的发票ID</returns>
        public async Task<APIRequst<int>> Handle(AddSalesInvoiceCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证参数
                if (string.IsNullOrEmpty(request.InvoiceNo))
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "发票编号不能为空" };
                }

                if (request.CustomerId <= 0)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "客户ID不能为空" };
                }

                if (request.InvoiceDetails == null || request.InvoiceDetails.Count == 0)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "发票明细不能为空" };
                }

                // 创建销售发票实体
                var salesInvoice = new SalesInvoice
                {
                    InvoiceNo = request.InvoiceNo,
                    OrderId = request.OrderId,
                    CustomerId = request.CustomerId,
                    InvoiceAmount = request.InvoiceAmount,
                    InvoiceDate = request.InvoiceDate,
                    InvoiceType = request.InvoiceType,
                    InvoiceStatus = request.InvoiceStatus,
                    TaxRate = request.TaxRate,
                    TaxAmount = request.TaxAmount,
                    SubtotalAmount = request.SubtotalAmount,
                    Remarks = request.Remarks,
                    CreateName = request.CreateName,
                    CreateTime = DateTime.Now,
                    UpdateTime = DateTime.Now,
                    isDel = false
                };

                // 添加销售发票到仓储
                int result = await _salesInvoiceRepository.Add(salesInvoice);
                if (result <= 0)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "保存发票失败" };
                }

                // 获取保存后自动生成的发票ID
                int invoiceId = salesInvoice.InvoiceId;
                if (invoiceId <= 0)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "发票ID生成失败" };
                }

                // 创建发票明细列表
                List<SalesInvoiceDetail> details = new List<SalesInvoiceDetail>();
                foreach (var detailDto in request.InvoiceDetails)
                {
                    var invoiceDetail = new SalesInvoiceDetail
                    {
                        InvoiceId = invoiceId, // 使用已生成的发票ID
                        ProductName = detailDto.ProductName,
                        ProductCode = string.Empty, // 可以从其他地方获取
                        Specifications = detailDto.Specification, // 映射规格型号
                        Unit = detailDto.Unit,
                        Quantity = detailDto.Quantity,
                        UnitPrice = detailDto.UnitPrice,
                        Amount = detailDto.Amount,
                        TaxRate = detailDto.TaxRate,
                        TaxAmount = detailDto.TaxAmount,
                        Remarks = detailDto.Remarks,
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now,
                        isDel = false
                    };

                    details.Add(invoiceDetail);
                }

                // 批量添加发票明细
                int detailCount = await _salesInvoiceDetailRepository.AddRange(details);
                if (detailCount != request.InvoiceDetails.Count)
                {
                    return new APIRequst<int> { Code = RequstCode.失败, Msg = "保存发票明细失败" };
                }

                // 返回创建成功的发票ID
                return new APIRequst<int> { Code = RequstCode.成功, Data = invoiceId, Msg = "添加成功" };
            }
            catch (Exception ex)
            {
                // 记录异常并返回失败结果，包含更详细的错误信息
                string errorMsg = GetFullExceptionMessage(ex);
                return new APIRequst<int> { Code = RequstCode.失败, Data = 0, Msg = $"添加失败：{errorMsg}" };
            }
        }

        /// <summary>
        /// 获取完整的异常信息，包括内部异常
        /// </summary>
        /// <param name="ex">异常对象</param>
        /// <returns>完整的异常信息字符串</returns>
        private string GetFullExceptionMessage(Exception ex)
        {
            if (ex.InnerException == null)
            {
                return ex.Message;
            }
            return $"{ex.Message} -> {GetFullExceptionMessage(ex.InnerException)}";
        }
    }
}